package com.jing21.learn.api.config;

import com.jing21.learn.common.learn.ApiResult;
import com.jing21.learn.common.learn.exception.ServiceException;
import com.jing21.learn.common.learn.exception.ServiceValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.PostConstruct;
import javax.inject.Named;
import java.util.Optional;

/**
 * 默认异常处理
 * Created by 郑靖 on 2017/10/9.
 */
@RestControllerAdvice
@Named
public class DefaultExceptionHandler {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 参数校验异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class, ServiceValidationException
            .class})
    public ApiResult argumentValidFail(Exception e) {

        String message = "参数异常";
        if (e instanceof MethodArgumentNotValidException) {

            MethodArgumentNotValidException manv = (MethodArgumentNotValidException) e;
            message = manv.getBindingResult().getFieldError().getDefaultMessage();
        } else if (e instanceof BindException) {

            BindException be = (BindException) e;
            message = be.getFieldError().getDefaultMessage();
        } else if (e instanceof ServiceValidationException) {

            ServiceValidationException sve = (ServiceValidationException) e;
            message = sve.getMessage();
        }
        return ApiResult.getError(message);
    }

    /**
     * RPC 异常
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ServiceException.class)
    public ApiResult feignFail(ServiceException le) {

        return ApiResult.getError(Optional.ofNullable(le.getCode()).orElse(10001L), le.getMeesgae());
    }

    /**
     * 未知的异常
     */
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    @ExceptionHandler(Exception.class)
    public ApiResult unknownFail(Exception e) {
        logger.error("发生未知错误", e);
        return ApiResult.getError(30001L, "未知的错误");
    }

    @PostConstruct
    public void postConstruct() {
        System.err.println("postConstruct");
    }
}
